<template>
	<view class="sunui-add-list">
		<view class="sunui-add-list-items" v-for="(item, index) in imgLists" :key="index">
			<image :src="item.url" :data-imgurl="item.url" @tap="showImgs" class="sunui-add-list-img" :mode="imgMode"></image>
			<view class="sunui-add-list-remove sunui-icons icon-close" :style="{ color: closeBtnColor }" @tap.stop="removeImg" :id="'sunui-items-img-' + index"></view>
			<!-- <view class="upload-progress"><progress :percent="item.progress" :stroke-width="progressSize" :activeColor="progressColor" :backgroundColor="progressBGColor" /></view> -->
			<view class="sunui-add-list-reup" @tap.stop="retry" :data-index="index" v-if="item.error">
				<text class="sunui-add-list-reup-icon sunui-icons icon-retry"></text>
				<text class="sunui-add-list-reup-text">失败重试</text>
			</view>
		</view>
		<view class="sunui-add-list-items sunui-add-list-btn" @tap="addImg" v-if="imgLists.length < maxFileNumber">
			<view class="sunui-add-list-btn-icon">+</view>
			<view class="sunui-add-list-btn-text">{{ btnName }}</view>
		</view>
	</view>
</template>
<script>
export default {
	props: {
		maxFileNumber: {
			type: Number,
			default: 9
		},
		btnName: {
			type: String,
			default: '添加照片'
		},
		items: {
			type: Array,
			default: function() {
				return [];
			}
		},
		closeBtnColor: {
			type: String,
			default: '#666666'
		},
		uploadServerUrl: {
			type: String,
			default: ''
		},
		progressSize: {
			type: Number,
			default: 1
		},
		progressColor: {
			type: String,
			default: '#27BD81'
		},
		progressBGColor: {
			type: String,
			default: '#F8F8F8'
		},
		fileName: { type: String, default: 'img' },
		formData: {
			type: Object,
			default: function() {
				return {};
			}
		},
		imgMode: { type: String, default: 'widthFix' },
		header: {
			type: Object,
			default: function() {
				return {};
			}
		}
	},
	data() {
		return {
			imgLists: [],
			updatting: false
		};
	},
	watch: {
		imgLists(newVal, oldVal) {
			if (!this.updatting) {
				this.$emit('change', newVal);
			}
		}
	},
	methods: {
		clearAllImgs() {
			this.imgLists = [];
		},
		addImg() {
			var num = this.maxFileNumber - this.imgLists.length;
			if (num < 1) {
				return false;
			}
			//uni.showLoading({title:""});
			uni.chooseImage({
				count: num,
				sizeType: ['compressed'],
				success: res => {
					for (let i = 0; i < res.tempFilePaths.length; i++) {
						this.imgLists.push({ url: res.tempFilePaths[i], progress: 0, error: false });
					}
					//uni.hideLoading();
				},
				complete: function() {
					//uni.hideLoading();
				},
				fail: function() {
					//uni.hideLoading();
				}
			});
		},
		removeImg(e) {
			var index = e.currentTarget.id.replace('sunui-items-img-', '');
			var removeImg = this.imgLists.splice(index, 1);
			this.$emit('removeImg', removeImg[0]);
		},
		showImgs(e) {
			var currentImg = e.currentTarget.dataset.imgurl;
			var imgs = [];
			for (let i = 0; i < this.imgLists.length; i++) {
				imgs.push(this.imgLists[i].url);
			}
			uni.previewImage({
				urls: imgs,
				current: currentImg
			});
		},
		upload(index) {
			if (this.updatting) {
				return;
			}
			this.updatting = true;
			if (!index) {
				index = 0;
			}
			uni.showLoading({ title: '图片上传中' });
			this.uploadBase(index);
		},
		retry(e) {
			var index = e.currentTarget.dataset.index;
			this.upload(index);
		},
		uploadBase(index) {
			// 全部上传完成
			if (index > this.imgLists.length - 1) {
				uni.hideLoading();
				this.updatting = false;
				this.$emit('uploaded', this.imgLists);
				return;
			}
			// 验证后端
			if (this.uploadServerUrl == '') {
				uni.showToast({ title: '请设置上传服务器地址', icon: 'none' });
				return;
			}
			// 检查是否是默认值
			if (this.imgLists[index].progress >= 1) {
				this.uploadBase(index + 1);
				return;
			}
			this.imgLists[index].error = false;
			// 创建上传对象
			const task = uni.uploadFile({
				url: this.uploadServerUrl,
				filePath: this.imgLists[index].url,
				name: 'file' || this.fileName,
				formData: this.formData,
				header: this.header,
				success: uploadRes => {
					uploadRes = JSON.parse(uploadRes.data);

					console.log('uploadRes', uploadRes);

					if (uploadRes.code != 0) {
						uni.showToast({ title: '上传失败 : ' + uploadRes.data, icon: 'none' });
						this.error(index);
					} else {
						//上传图片成功
						this.imgLists[index].progress = 100;
						this.imgLists[index].url = uploadRes.data;
						this.imgLists[index].result = uploadRes;
						this.uploadBase(index + 1);
					}
				},
				fail: e => {
					uni.showToast({ title: '上传失败，请点击图片重试', icon: 'none' });
					this.error(index);
				}
			});
			task.onProgressUpdate(res => {
				if (res.progress > 0) {
					this.imgLists[index].progress = res.progress;
					this.imgLists.splice(index, 1, this.imgLists[index]);
				}
			});
		},
		// 上传错误
		error(index) {
			this.updatting = false;
			setTimeout(() => {
				this.imgLists[index].progress = 0;
				this.imgLists[index].error = true;
				this.$emit('uploaderror');
			}, 500);
		},
		// 设置默认值
		setItems(items) {
			this.imgLists = [];
			for (let i = 0; i < items.length; i++) {
				this.imgLists.push({ url: items[i], progress: 100 });
			}
		}
	}
};
</script>
<style scoped>
.sunui-add-list {
	display: flex;
	flex-wrap: wrap;
}
.sunui-add-list-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.sunui-add-list-btn-text {
	font-size: 26rpx;
	line-height: 36rpx;
	text-align: center;
	color: #999999;
	width: 100%;
}
.sunui-add-list-btn-icon {
	font-size: 80rpx;
	height: 80rpx;
	line-height: 80rpx;
	margin-bottom: 20rpx;
	color: #999999;
}
.sunui-add-list-items {
	width: 211rpx;
	height: 222rpx;
	overflow: hidden;
	margin-top: 10rpx;
	margin-right: 19rpx;
	background: #f6f7f8;
	font-size: 0;
	position: relative;
	border-radius: 10rpx;
}
.sunui-add-list-image {
	width: 222rpx;
}
.sunui-add-list-remove {
	width: 50rpx;
	height: 50rpx;
	line-height: 50rpx;
	text-align: center;
	font-size: 40rpx;
	position: absolute;
	z-index: 5;
	right: 10rpx;
	top: 10rpx;
	color: #888888;
}
.upload-progress {
	position: absolute;
	z-index: 2;
	left: 0;
	bottom: 10rpx;
	width: 180rpx;
	padding: 0 21rpx;
}
.sunui-add-list-reup {
	position: absolute;
	z-index: 3;
	left: 0;
	top: 0rpx;
	width: 222rpx;
	height: 222rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: rgba(0, 0, 0, 0.3);
	flex-direction: column;
}
.sunui-add-list-reup-icon {
	text-align: center;
	width: 100%;
	color: #ffffff;
	display: block;
	font-size: 80rpx;
	line-height: 100rpx;
}
.sunui-add-list-reup-text {
	text-align: center;
	width: 100%;
	color: #ffffff;
	display: block;
	font-size: 20rpx;
	line-height: 30rpx;
}
.sunui-add-list-img {
	width: 222rpx;
}
</style>
